import React from 'react';
import { Input, message } from 'antd';
import { Form, Icon } from '@ant-design/compatible';
import { connect } from 'dva';
import md5 from '../../utils/md5';
import styles from './modifyPassword.css';
import { routerRedux } from 'dva/router';
import { delAuthority } from '../../utils/authority';
import { reloadAuthorized } from '../../utils/Authorized';
import { IconButton } from '../../components';

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 18 },
};
const tailFormItemLayout = {
  wrapperCol: { span: 20, offset: 4 },
};

class page extends React.Component {
  state = {
    loading: false,
    oldPasswd: null,
    newPasswd: null,
    newPasswd2: null,
  };

  // 提交密码更改
  funcSubmit = () => {
    const { form, dispatch } = this.props;
    form.validateFields((err, values) => {
      if (err) return false;

      const { oldPasswd, newPasswd, newPasswd2 } = values;
      if (newPasswd !== newPasswd2) {
        this.funcErrMsg('两次输入的新密码不一致，请检查后再次输入。', 'newPasswd2');
        return false;
      }
      if (newPasswd === oldPasswd) {
        this.funcErrMsg('新密码与旧密码相同！您在开玩笑吗？', 'newPasswd');
        return false;
      }

      this.setState({ loading: true });

      const reqApi = 'global';
      const payload = {
        oldPasswd: md5.md5(oldPasswd),
        newPasswd: md5.md5(newPasswd),
      };
      dispatch({
        type: reqApi + '/modifyPassword',
        payload,
      }).then(() => {
        const { props } = this;
        this.setState({ loading: false });
        const { success } = props[reqApi];
        if (!success) return;

        this.funcSubmitOK();
      });

      return true;
    });
  };

  // 登录密码更改成功
  funcSubmitOK = () => {
    delAuthority();
    reloadAuthorized();
    const { props } = this;
    props.dispatch(routerRedux.replace('/user/login'));
  };

  // 出错反馈
  funcErrMsg = (text, domId) => {
    message.warn(text);
    const domInput = document.getElementById(domId);
    if (domInput) domInput.focus();
  };

  // 密码输入框的内容改变事件
  funcPwChange = e => {
    const { value } = e.target;
    const id = e.target.getAttribute('data-id');
    this.state[id] = value === '' ? null : this.funcIco(id);
  };

  // 文本输入框右侧的小图标
  funcIco = (id, a = 0) => {
    const ico = a ? '' : '-o';
    return (
      <Icon
        type={'eye' + ico}
        className={styles.iconRight}
        data-id={id}
        onMouseDown={e => {
          let dom = e.target;
          dom = dom.getAttribute('d') ?
            dom.parentElement.parentElement : dom.parentElement;
          const id2 = dom.getAttribute('data-id');
          document.getElementById(id2).type = 'text';
          this.state[id] = this.funcIco(id, 1);
          this.setState({});
        }}
        onMouseUp={e => {
          let dom = e.target;
          dom = dom.getAttribute('d') ?
            dom.parentElement.parentElement : dom.parentElement;
          const id2 = dom.getAttribute('data-id');
          document.getElementById(id2).type = 'password';
          document.getElementById(id).focus();
          this.state[id] = this.funcIco(id);
          this.setState({});
        }}
      />
    );
  };

  render() {
    const { state, props } = this;
    const { getFieldDecorator } = props.form;

    return (
      <Form>
        <Form.Item label="当前密码" {...formItemLayout}>
          {getFieldDecorator('oldPasswd', {
            rules: [{ required: true, message: '请输入当前密码' }],
          })(
            <Input
              autoFocus
              type="password"
              maxLength={20}
              placeholder="请输入您现在的密码"
              prefix={<Icon type="key" className={styles.iconLeft} />}
              suffix={state.oldPasswd}
              data-id="oldPasswd"
              onChange={this.funcPwChange}
            />
          )}
        </Form.Item>
        <Form.Item label="新密码" {...formItemLayout}>
          {getFieldDecorator('newPasswd', {
            rules: [{ required: true, message: '请输入新密码' }],
          })(
            <Input
              type="password"
              maxLength={20}
              placeholder="请输入您的新密码"
              prefix={<Icon type="unlock" className={styles.iconLeft} />}
              suffix={state.newPasswd}
              data-id="newPasswd"
              onChange={this.funcPwChange}
            />
          )}
        </Form.Item>
        <Form.Item label="密码确认" {...formItemLayout}>
          {getFieldDecorator('newPasswd2', {
            rules: [{ required: true, message: '请再次输入新密码' }],
          })(
            <Input
              type="password"
              maxLength={20}
              placeholder="请再输一遍您的新密码"
              prefix={<Icon type="lock" className={styles.iconLeft} />}
              suffix={state.newPasswd2}
              data-id="newPasswd2"
              onChange={this.funcPwChange}
            />
          )}
        </Form.Item>
        <Form.Item {...tailFormItemLayout} style={{ marginBottom: 0 }}>
          <IconButton
            text='保存'
            loading={state.loading}
            className={styles.submit}
            onClick={this.funcSubmit}
          />
        </Form.Item>
      </Form>
    );
  }
}

const page2 = Form.create()(page);
export default connect(({ global }) => ({ global }))(page2);
